<template>
<CustomDialog
    v-model="dialogVisible"
    title="网关配置"
    width="1200px"
    top="5vh"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="gateway-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="网关名称" prop="gatewayName">
            <el-select
              v-model="formData.gatewayName"
              placeholder="请选择网关名称"
              style="width: 100%"
              @change="handleGatewayNameChange"
            >
              <el-option
                v-for="gateway in gatewayOptions"
                :key="gateway.value"
                :label="gateway.label"
                :value="gateway.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="网关ID号" prop="gatewayId">
            <el-select
              v-model="formData.gatewayId"
              placeholder="请选择网关ID"
              style="width: 100%"
              @change="handleGatewayIdChange"
            >
              <el-option
                v-for="id in gatewayIdOptions"
                :key="id.value"
                :label="id.label"
                :value="id.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input
              v-model="formData.deviceName"
              placeholder="请输入设备名称（用于软件显示）"
              maxlength="30"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="ESN号" prop="esnNumber">
            <el-input
              v-model="formData.esnNumber"
              placeholder="自动识别"
              readonly
              class="readonly-input"
            >
              <template #suffix>
                <el-icon class="auto-icon" @click="handleAutoRecognize">
                  <Refresh />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="设备ID号" prop="deviceId">
            <el-input-number
              v-model="formData.deviceId"
              :min="1"
              :max="30"
              :step="1"
              placeholder="设备ID"
              style="width: 100%"
              @change="handleDeviceIdChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供电类型" prop="powerType">
            <el-select
              v-model="formData.powerType"
              placeholder="请选择供电类型"
              style="width: 100%"
            >
              <el-option label="电池供电" value="battery" />
              <el-option label="有线供电" value="wired" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 设备管理区域 -->
      <el-divider content-position="left">设备管理</el-divider>
      <el-row :gutter="20">
        <el-col :span="24">
          <div class="device-management">
            <div class="device-actions" style="margin-bottom: 15px;">
               <el-button 
                 type="primary" 
                 :icon="Plus" 
                 @click="addDevice"
               >
                 添加设备 ({{ totalDeviceCount }}/{{ totalDeviceCapacity }})
               </el-button>
               <el-button 
                 type="danger" 
                 :icon="Delete" 
                 @click="removeSelectedDevices"
                 :disabled="selectedDevices.length === 0"
               >
                 删除选中 ({{ selectedDevices.length }})
               </el-button>
             </div>
            
            <!-- 设备列表 -->
            <el-table
              :data="paginatedDeviceList"
              @selection-change="handleDeviceSelectionChange"
              class="device-table"
              max-height="200"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="gatewayName" label="网关名称" width="120">
                <template #default="{ row }">
                  {{ row.gatewayName || `默认网关${row.gatewayId}` }}
                </template>
              </el-table-column>
              <el-table-column prop="gatewayIp" label="网关IP" width="120">
                <template #default="{ row }">
                  {{ row.gatewayIp || `默认网关${row.gatewayId}` }}
                </template>
              </el-table-column>
              <el-table-column prop="name" label="设备名称" width="120">
                <template #default="{ row }">
                  <div v-if="editingDeviceId === row.id" class="name-edit-container">
                    <el-input
                      v-model="editingDeviceName"
                      size="small"
                      maxlength="30"
                      @keyup.enter="saveDeviceName(row.id)"
                      @blur="cancelEdit"
                      style="width: 80px;"
                    />
                    <div class="edit-actions">
                      <el-button 
                        :icon="Check" 
                        size="small" 
                        type="primary" 
                        @click="saveDeviceName(row.id)"
                        style="margin-left: 4px;"
                      />
                      <el-button 
                        :icon="Close" 
                        size="small" 
                        @click="cancelEdit"
                        style="margin-left: 2px;"
                      />
                    </div>
                  </div>
                  <div v-else class="name-display-container">
                    <span>{{ row.name }}</span>
                    <el-button 
                      :icon="Edit" 
                      size="small" 
                      type="text" 
                      @click="startEdit(row.id, row.name)"
                      style="margin-left: 4px;"
                    />
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="id" label="设备ID" width="80" />
              <el-table-column prop="esn" label="ESN号" width="120" />
              <el-table-column prop="status" label="状态" width="80">
                <template #default="{ row }">
                  <el-tag :type="row.status === 'online' ? 'success' : 'danger'">
                    {{ row.status === 'online' ? '在线' : '离线' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template #default="{ row }">
                  <div class="device-actions">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click="openPowerTypeEditDialog(row)"
                    >
                      编辑
                    </el-button>
                    <el-button 
                      type="danger" 
                      size="small" 
                      @click="removeDevice(row.id)"
                    >
                      删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 设备列表分页 -->
            <div v-if="totalDeviceListPages > 1" class="device-list-pagination">
              <el-pagination
                v-model:current-page="currentDeviceListPage"
                :page-size="deviceListPageSize"
                :total="allDevices.length"
                layout="total, prev, pager, next"
                small
                @current-change="handleDeviceListPageChange"
              />
            </div>
          </div>
        </el-col>
      </el-row>
    </el-form>

    <!-- 网关管理表格 -->
    <el-divider content-position="left">网关管理</el-divider>
    <div class="gateway-management">
      <el-table :data="gatewayList" class="gateway-table" max-height="300">
        <el-table-column prop="name" label="网关名称" />
        <el-table-column prop="id" label="网关ID" />
        <el-table-column prop="deviceCount" label="设备数量" width="100">
          <template #default="{ row }">
            <el-tag>{{ getGatewayNumber(row.ip) }}/30</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.isConnected? 'success' : 'danger'">
              {{ row.isConnected ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button 
              type="info" 
              size="small" 
              @click="viewGatewayDetails(row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="loading">
          确认配置
        </el-button>
      </div>
    </template>
  </CustomDialog>

  <!-- 设备信息编辑对话框 -->
  <el-dialog
    v-model="powerTypeEditDialogVisible"
    title="编辑设备信息"
    width="450px"
    :before-close="closePowerTypeEditDialog"
  >
    <div class="device-edit-content">
      <el-form :model="editDeviceForm" label-width="100px">
        <el-form-item label="ESN号">
          <el-input v-model="editDeviceForm.esn" disabled />
          <div class="form-tip">ESN号不可修改</div>
        </el-form-item>
        
        <el-form-item label="设备ID" required>
          <el-input-number 
            v-model="editDeviceForm.id" 
            :min="1" 
            :max="999999"
            placeholder="请输入设备ID"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="供电类型" required>
          <el-radio-group v-model="editDeviceForm.powerType">
            <el-radio label="battery">电池供电</el-radio>
            <el-radio label="wired">有线供电</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closePowerTypeEditDialog">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmDeviceInfoChange"
          :disabled="!editDeviceForm.id || !editDeviceForm.powerType"
        >
          确认更改
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup lang="ts">
import CustomDialog from './CustomDialog.vue';
import { ref, computed, watch, nextTick, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Plus, Delete, Edit, Check, Close } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { gatewayStore } from '@/store/gateway'
import { moduleStore } from '@/store/module'
import { storeToRefs } from 'pinia'
import { WebsocketIo } from '@/utils/websocket'
import { channelNameDb } from '@/local/channelNameDb'

const gateway_store = gatewayStore()
const module_store = moduleStore()
const { gatewayList } = storeToRefs(gateway_store)
const { gateway_deviceList } = storeToRefs(module_store)
const { getGatewayNumber, getRandomPendingDevice } = module_store

// WebSocket实例引用
const wsInstance = ref<WebsocketIo | null>(null)


interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', data: FormData): void
}

interface FormData {
  gatewayName: number | string
  gatewayId: string
  deviceName: string
  esnNumber: string
  deviceId: number | null
  powerType: string
}

interface Device {
  id: number
  name: string
  esn: string
  powerType: string
  status: 'online' | 'offline'
  gatewayId?: string
  gatewayName?: string
  gatewayIp?: string
}

interface Gateway {
  name: string
  id: string
  deviceCount: number
  esn: string
  status: 'online' | 'offline'
  isConnected: boolean
  ip?: string;
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)

// 设备总数
const totalDeviceCount = ref(0);
const totalDeviceCapacity = computed(() => {
  return (gatewayList.value?.length || 0) * 30;
});


// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 表单数据
const formData = ref<FormData>({
  gatewayName: '',
  gatewayId: '',
  deviceName: '',
  esnNumber: '',
  deviceId: null,
  powerType: 'wired'
})

// 设备管理相关状态
const selectedDevices = ref<Device[]>([])

// 设备名称编辑相关状态
const editingDeviceId = ref<number | null>(null)
const editingDeviceName = ref('')

// 设备信息编辑对话框相关状态
const powerTypeEditDialogVisible = ref(false)
const currentEditDevice = ref<Device | null>(null)
const selectedPowerType = ref('')

// 编辑设备表单数据
const editDeviceForm = ref({
  id: null as number | null,
  esn: '',
  powerType: '',
  gatewayId: ''
})

// 设备ID分页相关
const currentDevicePage = ref(1)
const devicePageSize = ref(10)
const totalDevicePages = computed(() => Math.ceil(30 / devicePageSize.value))

// 设备列表分页相关
const currentDeviceListPage = ref(1)
const deviceListPageSize = ref(10)

// 响应式的设备列表数据
const deviceListData = ref<Device[]>([])

// 计算属性：获取当前网关的设备列表
const currentGatewayDevices = computed(() => {
  // 如果没有选择网关，返回空数组
  if (!formData.value.gatewayId) {
    return []
  }
  
  // 根据当前选择的网关ID过滤设备
  return deviceListData.value.filter(device => 
    device.gatewayId === String(formData.value.gatewayId)
  )
})

// 计算属性：获取所有设备列表（用于设备管理表格显示）
const allDevices = computed(() => {
  return deviceListData.value
})

// 更新设备列表数据
const updateDeviceListData = async () => {
  if (!gateway_deviceList.value) {
    deviceListData.value = []
    return
  }
  
  // 获取自定义名称
  let customNames: Map<string, string> = new Map()
  try {
    customNames = await channelNameDb.getAllNames()
  } catch (error) {
    console.error('加载设备自定义名称失败:', error)
  }
  
  const allDevices: Device[] = []
  
  // 遍历所有网关的设备
  for (const [gatewayIp, devices] of gateway_deviceList.value.entries()) {
    const gateway = gatewayList.value?.find(g => g.ip === gatewayIp)
    
    devices.forEach((device, index) => {
      // 过滤掉没有ESN的设备
      if (!device?.esn || device.esn.trim() === '') {
        return
      }
      
      const deviceId = parseInt(device?.deviceId || '') || index + 1
      const dbKey = `${gatewayIp}-${deviceId}`
      const customName = customNames.get(dbKey)
      
      // 🔥 修复：从本地存储读取设备供电类型
      const powerTypeKey = `powerType_${gatewayIp}_${deviceId}`;
      const savedPowerType = localStorage.getItem(powerTypeKey);
      const powerType = savedPowerType || 'wired'; // 默认有线供电
      
      allDevices.push({
         id: deviceId,
         name: customName || `监测点${deviceId}`,
         esn: device.esn,
         powerType: powerType, // 使用从本地存储读取的供电类型
         status: device?.status ? 'online' : 'offline',
         gatewayId: gateway?.id || '',
         gatewayName: gateway?.name || `默认网关${gateway?.id || ''}`,
         gatewayIp: gatewayIp
       })
    })
  }
  
  deviceListData.value = allDevices
}

// 加载设备自定义名称
const loadDeviceCustomNames = async () => {
  try {
    const currentIp = gateway_store.currentIp
    if (!currentIp) return
    
    const customNames = await channelNameDb.getAllNames()
    
    // 更新设备列表中的自定义名称
    currentGatewayDevices.value.forEach(device => {
      const dbKey = `${currentIp}-${device.id}`
      const customName = customNames.get(dbKey)
      if (customName) {
        device.name = customName
      }
    })
  } catch (error) {
    console.error('加载设备自定义名称失败:', error)
  }
}

// 分页后的设备列表 - 使用所有设备数据
const paginatedDeviceList = computed(() => {
  const start = (currentDeviceListPage.value - 1) * deviceListPageSize.value
  const end = start + deviceListPageSize.value
  return allDevices.value.slice(start, end)
})

// 更新设备列表分页总数计算
const totalDeviceListPages = computed(() => Math.ceil(allDevices.value.length / deviceListPageSize.value))

// 表单验证规则
const rules: FormRules = {
  gatewayName: [
    { required: true, message: '请选择网关名称', trigger: 'change' }
  ],
  gatewayId: [
    { required: true, message: '请选择网关ID', trigger: 'change' }
  ],
  deviceName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { min: 2, max: 50, message: '设备名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  deviceId: [
    { required: true, message: '请选择设备ID', trigger: 'change' }
  ],
  powerType: [
    { required: true, message: '请选择供电类型', trigger: 'change' }
  ]
}

// 网关选项
const gatewayOptions = computed(() => {
  return gatewayList.value?.map(gateway => ({
    label: gateway.name || `默认网关${gateway.id}`,
    value: gateway.id
  })) || []
})

// 网关ID选项
const gatewayIdOptions = computed(() => {
  return gatewayList.value?.map(gateway => ({
    label: gateway.id,
    value: gateway.id
  })) || []
})

// 设备ID选项（1-30，支持分页）
const deviceIdOptions = computed(() => {
  return Array.from({ length: 30 }, (_, i) => i + 1)
})

// 分页后的设备ID选项
const paginatedDeviceIds = computed(() => {
  const start = (currentDevicePage.value - 1) * devicePageSize.value
  const end = start + devicePageSize.value
  return deviceIdOptions.value.slice(start, end)
})

// 处理设备ID分页变化
const handleDevicePageChange = (page: number) => {
  currentDevicePage.value = page
}

// 处理设备列表分页变化
const handleDeviceListPageChange = (page: number) => {
  currentDeviceListPage.value = page
}

// 处理网关名称变化
const handleGatewayNameChange = async (value: number) => {
  const selectedGateway = gatewayList.value?.find(g => g.id === value)
  if (selectedGateway) {
    formData.value.gatewayId = selectedGateway.id.toString()
  }
  
  // 自动设置设备ID为当前网关下最大设备ID + 1
  const maxDeviceId = getMaxDeviceIdForCurrentGateway(value)
  const nextDeviceId = maxDeviceId + 1
  
  // 确保设备ID不超过30
  if (nextDeviceId <= 30) {
    formData.value.deviceId = nextDeviceId
  } else {
    // 如果超过30，则使用下一个可用的ID
    const availableId = getNextAvailableDeviceId()
    formData.value.deviceId = availableId
  }
}

// 处理网关ID变化
const handleGatewayIdChange = async (value: string) => {
  // 自动设置设备ID为当前网关下最大设备ID + 1
  const maxDeviceId = getMaxDeviceIdForCurrentGateway(value)
  const nextDeviceId = maxDeviceId + 1
  
  // 确保设备ID不超过30
  if (nextDeviceId <= 30) {
    formData.value.deviceId = nextDeviceId
  } else {
    // 如果超过30，则使用下一个可用的ID
    const availableId = getNextAvailableDeviceId()
    formData.value.deviceId = availableId
  }
}

// 新增：处理自动识别点击事件
const handleAutoRecognize = async () => {
  console.log('🔍 [DEBUG] 开始自动识别设备')
  console.log('🔍 [DEBUG] 当前待入网设备列表:', module_store.pendingDevices)
  console.log('🔍 [DEBUG] 待入网设备数量:', module_store.pendingDevices.length)
  
  const randomESN = module_store.getRandomPendingDevice()
  console.log('🔍 [DEBUG] 获取到的随机ESN:', randomESN)
  
  if (!randomESN) {
    console.log('🔍 [DEBUG] 没有可用的待入网设备，尝试请求更新')
    // 尝试请求待入网设备数据
    try {
    // 再次尝试获取
      const retryESN = module_store.getRandomPendingDevice()
      console.log('🔍 [DEBUG] 重试获取的ESN:', retryESN)
      
      if (!retryESN) {
        ElMessage.warning('当前没有可用的待入网设备')
        return
      }
      
      formData.value.esnNumber = retryESN

      const response = await sendWebSocketCommand({
        action: 'getPendingDevices',
        gatewayIp: gateway_store.currentIp
      })
      console.log('🔍 [DEBUG] 请求待入网设备响应:', response)
      
      
    } catch (error) {
      console.error('🔍 [DEBUG] 请求待入网设备失败:', error)
      ElMessage.warning('获取待入网设备失败，请手动输入ESN')
      return
    }
  } else {
    formData.value.esnNumber = randomESN
  }
  
  console.log('🔍 [DEBUG] 最终设置的ESN:', formData.value.esnNumber)
  ElMessage.success(`已自动识别设备ESN: ${formData.value.esnNumber}`)
}

// 更新设备列表显示
const updateDeviceListDisplay = () => {
  // 重置分页
  currentDeviceListPage.value = 1
  // 清空选中的设备
  selectedDevices.value = []
}
// 获取下一个可用的设备ID
const getNextAvailableDeviceId = () => {
  // 如果没有选择网关，返回1
  if (!formData.value.gatewayId) {
    return 1
  }
  
  // 获取当前网关下已存在的设备ID
  const existingIds = currentGatewayDevices.value.map(device => device.id)
  
  // 查找1-30范围内第一个可用的ID
  for (let i = 1; i <= 30; i++) {
    if (!existingIds.includes(i)) {
      return i
    }
  }
  return null
}

// 获取当前网关下最大设备ID
const getMaxDeviceIdForCurrentGateway = (gatewayId?: number | string) => {
  // 使用传入的网关ID或当前表单中的网关ID
  const targetGatewayId = gatewayId || formData.value.gatewayId
  
  if (!targetGatewayId) {
    return 0 // 如果没有网关ID，返回0
  }
  
  // 过滤出指定网关的设备
  const targetDevices = deviceListData.value.filter(device => 
    device.gatewayId === String(targetGatewayId)
  )
  
  if (targetDevices.length === 0) {
    return 0 // 如果没有设备，返回0
  }
  
  const deviceIds = targetDevices.map(device => device.id)
  return Math.max(...deviceIds)
}

// 检查设备ID是否已存在（在当前选择的网关下）
const isDeviceIdExists = (deviceId: number, targetGatewayIp?: string) => {
  // 如果没有选择网关，返回false
  if (!formData.value.gatewayId && !targetGatewayIp) {
    return false
  }
  
  // 🔥 增强：支持指定网关IP进行检查
  if (targetGatewayIp) {
    // 检查指定网关下的设备ID是否存在
    const gatewayDevices = module_store.gateway_deviceList.get(targetGatewayIp) || []
    return gatewayDevices.some(device => {
      const existingDeviceId = parseInt(device?.deviceId || '') || 0
      return existingDeviceId === deviceId
    })
  }
  
  // 只检查当前选择网关下的设备ID
  return currentGatewayDevices.value.some(device => device.id === deviceId)
}

const isEsnExists = (esn: string, targetGatewayIp?: string) => {
  // 如果没有选择网关，返回false
  if (!formData.value.gatewayId && !targetGatewayIp) {
    return false
  }
  
  // 支持指定网关IP进行检查
  if (targetGatewayIp) {
    // 检查指定网关下的ESN是否存在
    const gatewayDevices = module_store.gateway_deviceList.get(targetGatewayIp) || []
    return gatewayDevices.some(device => device?.esn === esn)
  }
  
  // 检查当前选择网关下的ESN
  return currentGatewayDevices.value.some(device => device.esn === esn)
}

// 处理设备ID变化事件
const handleDeviceIdChange = (value: number | null) => {
  if (value && isDeviceIdExists(value)) {
    ElMessage.warning(`设备ID ${value} 已存在，请选择其他ID`)
    // 自动设置为下一个可用ID
    const nextId = getNextAvailableDeviceId()
    if (nextId) {
      formData.value.deviceId = nextId
    }
  }
}

// 生成随机ESN
const generateRandomESN = () => {
  const prefix = 'FFT'
  const randomNumber = Math.floor(Math.random() * 100000000).toString().padStart(8, '0')
  return prefix + randomNumber
}

// 设备名称编辑相关方法
const startEdit = (deviceId: number, currentName: string) => {
  editingDeviceId.value = deviceId
  editingDeviceName.value = currentName
  
  // 使用 nextTick 确保输入框已渲染，然后聚焦
  nextTick(() => {
    const inputElement = document.querySelector('.name-edit-container .el-input__inner') as HTMLInputElement
    if (inputElement) {
      inputElement.focus()
      inputElement.select()
    }
  })
}

const cancelEdit = () => {
  editingDeviceId.value = null
  editingDeviceName.value = ''
}

const saveDeviceName = async (deviceId: number) => {
  if (!editingDeviceName.value.trim()) {
    ElMessage.warning('设备名称不能为空')
    return
  }
  
  if (editingDeviceName.value.length > 30) {
    ElMessage.warning('设备名称不能超过30个字符')
    return
  }
  
  try {
    // 找到要编辑的设备，获取其网关IP
    const deviceToEdit = deviceListData.value.find(device => device.id === deviceId)
    if (!deviceToEdit || !deviceToEdit.gatewayIp) {
      ElMessage.error('无法找到设备信息')
      return
    }
    
    const gatewayIp = deviceToEdit.gatewayIp
    
    // 保存到 IndexedDB
    await channelNameDb.saveName(gatewayIp, deviceId, editingDeviceName.value.trim())
    
    // 找到对应的网关ID
    const gateway = gatewayList.value?.find(g => g.ip === gatewayIp)
    if (gateway) {
      // 同时更新 module store 中的数据
      await module_store.updateChannelName(
        parseInt(gateway.id) || 0, 
        deviceId, 
        editingDeviceName.value.trim()
      )
    }
    
    // 重新加载设备列表数据以显示最新的名称
    await updateDeviceListData()
    
    ElMessage.success('设备名称修改成功')
    cancelEdit()
    
  } catch (error) {
    console.error('保存设备名称失败:', error)
    ElMessage.error('保存设备名称失败：' + (error as Error).message)
  }
}

// 设备信息编辑对话框相关方法
const openPowerTypeEditDialog = (device: Device) => {
  currentEditDevice.value = device
  // 初始化编辑表单数据
  editDeviceForm.value = {
    id: device.id,
    esn: device.esn,
    powerType: device.powerType,
    gatewayId: device.gatewayIp, // 使用网关IP地址而不是网关ID
  }
  powerTypeEditDialogVisible.value = true
}

const closePowerTypeEditDialog = () => {
  powerTypeEditDialogVisible.value = false
  currentEditDevice.value = null
  selectedPowerType.value = ''
  // 重置编辑表单
  editDeviceForm.value = {
    id: null,
    esn: '',
    powerType: ''
  }
}

const confirmDeviceInfoChange = async () => {
  if (!currentEditDevice.value || !editDeviceForm.value.id || !editDeviceForm.value.powerType) {
    ElMessage.warning('请填写完整的设备信息')
    return
  }
  
  try {
    // 检查设备ID是否重复（排除当前设备）
    const isDuplicateId = deviceListData.value.some(device => 
      device.id === editDeviceForm.value.id && device.id !== currentEditDevice.value!.id
    )
    
    if (isDuplicateId) {
      ElMessage.error(`设备ID ${editDeviceForm.value.id} 已存在，请选择其他ID`)
      return
    }
    
    // 供电类型转换：有线供电=3，电池供电=2
    const powerTypeNumber = editDeviceForm.value.powerType === 'wired' ? 3 : 2
    
    // 找到对应的设备并更新信息
    const deviceIndex = deviceListData.value.findIndex(device => device.id === currentEditDevice.value!.id)
    
    if (deviceIndex !== -1) {
      const oldDeviceId = currentEditDevice.value.id
      const newDeviceId = editDeviceForm.value.id
      
      // 更新本地数据
      deviceListData.value[deviceIndex].id = newDeviceId
      deviceListData.value[deviceIndex].powerType = editDeviceForm.value.powerType
      
      // 更新本地存储中的供电类型
      const device = currentEditDevice.value
      const powerTypeKey = `powerType_${device.gatewayIp}_${newDeviceId}`;
      localStorage.setItem(powerTypeKey, editDeviceForm.value.powerType);
      console.log(`✅ [DEBUG] 设备信息已更新到localStorage: ${powerTypeKey} -> ${editDeviceForm.value.powerType}`);
      
      // 如果设备ID发生变化，需要清理旧的localStorage记录
      if (oldDeviceId !== newDeviceId) {
        const oldPowerTypeKey = `powerType_${device.gatewayIp}_${oldDeviceId}`;
        localStorage.removeItem(oldPowerTypeKey);
        console.log(`🗑️ [DEBUG] 已清理旧设备ID的localStorage记录: ${oldPowerTypeKey}`);
      }
      
      // 通过WebSocket发送update指令到后端
      const payload = {
        action: 'gateway',
        type: 'update',
        esn: currentEditDevice.value.esn,
        gatewayId: currentEditDevice.value.gatewayIp, // 使用网关IP地址而不是网关ID
        powerType: powerTypeNumber,
        id: newDeviceId
      }
      
      if (wsInstance.value) {
        wsInstance.value.sendMessage(JSON.stringify(payload))
        console.log('📤 [DEBUG] 发送设备更新指令:', payload)
      } else {
        console.warn('⚠️ [DEBUG] WebSocket实例不可用，无法发送更新指令')
      }
      
      ElMessage.success('设备信息修改成功')
      closePowerTypeEditDialog()
      
      // 强制触发响应式更新
      deviceListData.value = [...deviceListData.value]
    } else {
      ElMessage.error('找不到对应的设备')
    }
    
  } catch (error) {
    console.error('修改设备信息失败:', error)
    ElMessage.error('修改设备信息失败：' + (error as Error).message)
  }
}

// 添加设备 - 使用顶部表单
const addDevice = async () => {
  // 验证必填参数
  const { gatewayName, gatewayId, deviceName, deviceId, powerType, esnNumber } = formData.value;
  if (!gatewayName || !gatewayId || !deviceName || !deviceId || !powerType) {
    ElMessage.error('参数不能为空');
    return;
  }

  // 使用gatewayName作为实际的网关ID（因为下拉框绑定的是网关ID）
  const actualGatewayId = Number(gatewayName);

  // 根据选择的网关ID获取对应的网关IP
  const selectedGateway = gatewayList.value?.find(g => g.id === actualGatewayId);
  if (!selectedGateway || !selectedGateway.ip) {
    ElMessage.error('未找到选择的网关信息');
    return;
  }

  const targetGatewayIp = selectedGateway.ip;

  // 🔥 增强：检查设备ID是否重复（在指定的网关下）
  if (deviceId && isDeviceIdExists(deviceId, targetGatewayIp)) {
    ElMessage.error(`设备ID ${deviceId} 在网关 ${gatewayName} 下已存在，请选择其他ID`);
    return;
  }

  // 🔥 新增：检查ESN是否重复（在指定的网关下）
  if (esnNumber && isEsnExists(esnNumber, targetGatewayIp)) {
    ElMessage.error(`ESN ${esnNumber} 在网关 ${gatewayName} 下已存在，请选择其他ESN`);
    return;
  }

  if (currentGatewayDevices.value.length >= 30) {
    ElMessage.warning('当前网关设备数量已达到上限（30台）');
    return;
  }

  // ESN号是只读的，由其他逻辑生成，这里假设它已存在
  if (!esnNumber) {
    ElMessage.error('ESN号不能为空，请先选择网关以自动生成');
    return;
  }

  loading.value = true;

  try {
    // 构建添加设备的payload - 使用选择的网关IP
    const payload = {
      action: 'gateway',
      type: 'add',
      gatewayId: targetGatewayIp,
      esn: esnNumber,
      id: deviceId,
      powerType: powerType === "wire"? 3 : 2,
    };

    // WebSocket发送添加设备的指令
    wsInstance.value?.sendMessage(JSON.stringify(payload));

    // 模拟成功响应
    ElMessage.success(`设备 ${deviceName} (ID: ${deviceId}) 已添加到网关 ${gatewayName}!`);

    // 添加新设备到设备列表 - 使用选择的网关IP
    const currentDevices = module_store.gateway_deviceList.get(targetGatewayIp) || [];
    
    // 创建新设备对象
    const newDevice = {
      deviceId: deviceId.toString(),
      esn: esnNumber,
      status: true, // 新添加的设备默认在线
      name: deviceName,
      gatewayIp: targetGatewayIp,
    };
    
    // 添加新设备到列表
    const updatedDevices = [...currentDevices, newDevice];
    
    // 更新设备列表 - 使用选择的网关IP
    await module_store.setDevice(updatedDevices);
    
    // 🔥 新增：将设备名称保存到IndexedDB - 使用选择的网关IP
    try {
      await channelNameDb.saveName(targetGatewayIp, deviceId, deviceName);
      console.log(`✅ [DEBUG] 设备名称已保存到IndexedDB: ${targetGatewayIp}-${deviceId} -> ${deviceName}`);
      
      // 🔥 新增：保存设备供电类型到本地存储
      const powerTypeKey = `powerType_${targetGatewayIp}_${deviceId}`;
      localStorage.setItem(powerTypeKey, powerType);
      console.log(`✅ [DEBUG] 设备供电类型已保存到localStorage: ${powerTypeKey} -> ${powerType}`);
      
      // 🔥 新增：保存成功后，触发模块列表重新加载以更新显示
      await module_store.getModuleList(selectedGateway.id, targetGatewayIp);
      console.log(`✅ [DEBUG] 模块列表已重新加载，设备名称应已更新`);
    } catch (error) {
      console.error('❌ [ERROR] 保存设备名称到IndexedDB失败:', error);
      ElMessage.warning('设备添加成功，但名称保存失败，请手动重命名');
    }
    
    // 🔥 新增：从待入网设备列表中移除已使用的ESN
    const removeSuccess = module_store.removePendingDevice(esnNumber);
    if (removeSuccess) {
      console.log(`✅ [DEBUG] 已从待入网设备列表中移除ESN: ${esnNumber}`);
      console.log(`📊 [DEBUG] 当前待入网设备数量: ${module_store.pendingDevices.length}`);
    } else {
      console.warn(`⚠️ [DEBUG] 未能从待入网设备列表中找到ESN: ${esnNumber}`);
    }
    
    // 触发统计数据更新 - 通过访问getter来强制重新计算
    const totalDevices = module_store.get_all_devices_num;
    const onlineDevices = module_store.online_num;
    
    console.log(`📊 设备统计更新 - 总设备数: ${totalDevices}, 在线设备数: ${onlineDevices}`);
    ElMessage.info(`当前系统设备统计 - 在线: ${onlineDevices}/${totalDevices}`);

    // 更新设备列表数据以反映新添加的设备
    await updateDeviceListData();

    // 自动设置下一个可用的设备ID（递增1）
    formData.value.deviceId = (formData.value.deviceId || 0) + 1
    
    // 确保新的设备ID不超过最大值且不重复
    let newDeviceId = formData.value.deviceId
    while (newDeviceId <= 30 && isDeviceIdExists(newDeviceId)) {
      newDeviceId++
    }
    
    if (newDeviceId <= 30) {
      formData.value.deviceId = newDeviceId
    } else {
      // 如果超过30，则寻找第一个可用ID
      const nextId = getNextAvailableDeviceId()
      if (nextId) {
        formData.value.deviceId = nextId
      }
    }
    
    // 只清空设备名称字段
    formData.value.deviceName = ''
    
    // 从待入网设备列表中获取随机ESN
    const randomESN = module_store.getRandomPendingDevice()
    if (randomESN) {
      formData.value.esnNumber = randomESN
      console.log(`🔄 [DEBUG] 从待入网设备列表获取ESN: ${randomESN}`)
    } else {
      // 如果待入网设备列表为空，显示提示信息
      ElMessage.info('所有设备都已入网啦！')
      console.log('📋 [DEBUG] 待入网设备列表为空，所有设备都已入网')
      formData.value.esnNumber = '' // 清空ESN字段
    }
    
    
  } catch (error) {
    console.error('添加设备失败:', error);
    ElMessage.error('添加设备失败：' + (error as Error).message);
  } finally {
    loading.value = false;
  }
};


// WebSocket 发送指令方法
const sendWebSocketCommand = async (payload: any): Promise<any> => {
  return new Promise<any>((resolve, reject) => {
    if (!wsInstance.value || !wsInstance.value.websocketIsNormal()) {
      return reject(new Error('WebSocket 未连接'));
    }
    
    const responses: any[] = [];
    let timeoutId: any;
    
    const handler = (event: CustomEvent) => {
      const data = event.detail;
      console.log('GatewayConfigDialog: 收到WebSocket消息', data);
      
      // 检查是否是网关指令响应
      if (data.action === 'gatewayCommandResponse' || 
          (data.action === 'gateway_result' && data.type) ||
          // 增加对删除设备响应的识别
          (data.action === 'gateway' && data.type === 'delete') ||
          // 兼容可能的其他删除响应格式
          (data.type === 'delete' && (data.success !== undefined || data.result !== undefined)) ||
          // 🔥 新增：更宽泛的删除响应识别
          (payload.type === 'delete' && (data.success !== undefined || data.result !== undefined || data.status !== undefined))) {
        console.log('GatewayConfigDialog: 匹配到指令响应', data);
        responses.push(data);
        // 每次收到响应都重置超时，保证能收集连续响应
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
          window.removeEventListener('websocket-message', handler as EventListener);
          resolve(responses.length ? responses[responses.length - 1] : { success: false, message: '未收到有效响应' });
        }, 1500); // 1.5秒内无新响应则判定收集完毕
      }
    };
    
    // 监听全局WebSocket消息事件
    window.addEventListener('websocket-message', handler as EventListener);
    wsInstance.value.sendMessage(JSON.stringify(payload));
    
    // 最长等待5秒
    timeoutId = setTimeout(() => {
      window.removeEventListener('websocket-message', handler as EventListener);
      reject(new Error('等待响应超时'));
    }, 5000);
  });
}

// 解析WebSocket响应的通用方法
const parseWebSocketResponse = (response: any) => {
  let parsedResponse = response;
  if (typeof response === 'string') {
    try {
      parsedResponse = JSON.parse(response);
      // 如果是数组，取最后一个元素
      if (Array.isArray(parsedResponse) && parsedResponse.length > 0) {
        parsedResponse = parsedResponse[parsedResponse.length - 1];
      }
    } catch (e) {
      console.error('解析响应失败:', e);
      parsedResponse = { success: false, message: '响应格式错误' };
    }
  }
  
  // 🔥 增强success字段的判断逻辑
  if (parsedResponse.success === undefined) {
    // 如果没有success字段，尝试从其他字段推断
    if (parsedResponse.result !== undefined) {
      parsedResponse.success = parsedResponse.result === 'success' || parsedResponse.result === true || parsedResponse.result === 'ok';
    } else if (parsedResponse.status !== undefined) {
      parsedResponse.success = parsedResponse.status === 'success' || parsedResponse.status === 'ok' || parsedResponse.status === true;
    } else if (parsedResponse.code !== undefined) {
      // 新增：支持通过code字段判断成功
      parsedResponse.success = parsedResponse.code === 0 || parsedResponse.code === 200 || parsedResponse.code === '0' || parsedResponse.code === '200';
    } else if (parsedResponse.error === undefined && parsedResponse.message !== 'error') {
      // 如果没有错误信息，且不是明确的错误消息，则认为成功
      parsedResponse.success = true;
    }
  }
  
  // 🔥 新增：如果仍然无法确定成功状态，但有明确的错误信息，则标记为失败
  if (parsedResponse.success === undefined) {
    if (parsedResponse.error || parsedResponse.message === 'error' || parsedResponse.message?.includes('失败') || parsedResponse.message?.includes('错误')) {
      parsedResponse.success = false;
    } else {
      // 默认认为成功（保守策略）
      parsedResponse.success = true;
    }
  }
  
  console.log('🔍 [DEBUG] 解析后的响应:', parsedResponse);
  
  return parsedResponse;
};

// 更新设备列表的通用方法
const updateDeviceListAfterDelete = async (deletedDeviceIds: number[]) => {
  const currentIp = gateway_store.currentIp;
  if (!currentIp) {
    console.error('当前网关IP不存在');
    return;
  }

  const currentDevices = module_store.gateway_deviceList.get(currentIp) || [];
  const updatedDevices = currentDevices.filter(device => 
    !deletedDeviceIds.includes(parseInt(device?.deviceId || '0'))
  );
  
  console.log(`🗑️ [DEBUG] 删除前设备数量: ${currentDevices.length}`);
  console.log(`🗑️ [DEBUG] 要删除的设备ID: ${deletedDeviceIds}`);
  console.log(`🗑️ [DEBUG] 删除后设备数量: ${updatedDevices.length}`);
  
  // 更新设备列表 - 确保触发响应式更新
  await module_store.setDevice(currentIp, updatedDevices);
  
  // 强制触发响应式更新 - 通过重新设置Map来确保Vue检测到变化
  const newDeviceMap = new Map(module_store.gateway_deviceList);
  newDeviceMap.set(currentIp, updatedDevices);
  module_store.gateway_deviceList = newDeviceMap;
  
  // 清空选中状态
  selectedDevices.value = [];
  
  console.log(`🗑️ [DEBUG] 设备列表已更新，当前设备数量：${updatedDevices.length}/30`);
  
  // 手动更新设备总数和在线设备数
  module_store.updateDeviceCounts();
  
  return updatedDevices.length;
};

// 单个设备删除功能
const removeDevice = async (deviceId: number) => {
  try {
    await ElMessageBox.confirm("此操作将永久删除该设备, 是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 找到要删除的设备信息
    const deviceToDelete = currentGatewayDevices.value.find(device => device.id === deviceId);
    if (!deviceToDelete) {
      ElMessage.error('设备不存在');
      return;
    }

    loading.value = true;

    const payload = {
      action: "gateway",
      type: 'delete',
      gatewayId: gateway_store.currentIp,
      id: deviceId
    };

    const response = await sendWebSocketCommand(payload);
    console.log('🗑️ [DEBUG] 删除设备响应:', response);
    
    const parsedResponse = parseWebSocketResponse(response);
    console.log('🗑️ [DEBUG] 解析后的删除响应:', parsedResponse);
    
    if (parsedResponse && parsedResponse.success) {
      ElMessage.success("删除设备成功");
      
      // 🔥 新增：将删除设备的ESN重新添加回待入网设备列表
      if (deviceToDelete.esn) {
        const addSuccess = module_store.addPendingDevice(deviceToDelete.esn);
        if (addSuccess) {
          console.log(`✅ [DEBUG] 已将ESN重新添加回待入网设备列表: ${deviceToDelete.esn}`);
          console.log(`📊 [DEBUG] 当前待入网设备数量: ${module_store.pendingDevices.length}`);
        } else {
          console.warn(`⚠️ [DEBUG] ESN已存在于待入网设备列表中: ${deviceToDelete.esn}`);
        }
      }
      
      // 更新设备列表
      const remainingCount = await updateDeviceListAfterDelete([deviceId]);
      
      // 触发统计数据更新 - 通过访问getter来强制重新计算
      const totalDevices = module_store.get_all_devices_num;
      const onlineDevices = module_store.online_num;
      
      console.log(`📊 设备统计更新 - 总设备数: ${totalDevices}, 在线设备数: ${onlineDevices}`);
      ElMessage.info(`设备已删除，当前网关设备数量：${remainingCount}/30`);

      // 🔥 新增：删除设备成功后，发送停止闪光事件
      const stopFlashEvent = new CustomEvent('custom-event', {
        detail: {
          type: 'stopFlash',
          ID: deviceId
        }
      });
      window.dispatchEvent(stopFlashEvent);
      console.log(`💡 [DEBUG] 已发送停止闪光事件，设备ID: ${deviceId}`);

      // 🔥 优化：删除设备后，智能更新表单中的设备ID
      const nextAvailableId = getNextAvailableDeviceId();
      if (nextAvailableId) {
        // 总是更新为最小的可用ID，确保ID得到有效回收利用
        formData.value.deviceId = nextAvailableId;
        console.log(`🔄 [DEBUG] 设备ID已回收，表单设备ID更新为最小可用ID: ${nextAvailableId}`);
        
        // 如果删除的是当前表单中的ID，给出特别提示
        if (formData.value.deviceId === deviceId) {
          ElMessage.success(`设备ID ${deviceId} 已回收，表单已更新为下一个可用ID: ${nextAvailableId}`);
        }
      } else {
        // 如果没有可用ID，清空表单ID
        formData.value.deviceId = 1;
        console.log('🔄 [DEBUG] 没有可用ID，重置为ID 1');
      }
    } else {
      ElMessage.error(`删除设备失败: ${parsedResponse?.message || '未知错误'}`);
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除设备时发生错误:", error);
      ElMessage.error(`删除设备失败: ${(error as Error).message}`);
    }
  } finally {
    loading.value = false;
  }
};

// 批量删除选中设备功能 - 使用for循环逐个删除
const removeSelectedDevices = async () => {
  if (selectedDevices.value.length === 0) {
    ElMessage.warning('请先选择要删除的设备')
    return
  }
  
  try {
    // 确认批量删除
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedDevices.value.length} 个设备吗？此操作不可撤销。`,
      '批量删除设备',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    loading.value = true;
    let successCount = 0;
    let failCount = 0;
    const errors: string[] = [];
    const successfullyDeletedIds: number[] = [];
    const successfullyDeletedDevices: Device[] = []; // 🔥 新增：记录成功删除的设备信息

    // 使用for循环逐个删除设备，增加重试机制
    for (let i = 0; i < selectedDevices.value.length; i++) {
      const device = selectedDevices.value[i];
      let retryCount = 0;
      const maxRetries = 2;
      let deleteSuccess = false;

      while (retryCount <= maxRetries && !deleteSuccess) {
        try {
          const payload = {
            action: 'gateway',
            type: 'delete',
            gatewayId: gateway_store.currentIp,
            id: device.id
          };

          console.log(`正在删除设备${device.id}... (尝试 ${retryCount + 1}/${maxRetries + 1})`);
          const response = await sendWebSocketCommand(payload);
          console.log(`删除设备${device.id}响应:`, response);
          
          const parsedResponse = parseWebSocketResponse(response);
          
          if (parsedResponse && parsedResponse.success) {
            successCount++;
            successfullyDeletedIds.push(device.id);
            successfullyDeletedDevices.push(device); // 🔥 新增：记录成功删除的设备
            console.log(`设备${device.id}删除成功`);
            deleteSuccess = true;
          } else {
            console.error(`设备${device.id}删除失败 (尝试 ${retryCount + 1}):`, parsedResponse?.message);
            if (retryCount === maxRetries) {
              failCount++;
              errors.push(`设备${device.id}: ${parsedResponse?.message || '删除失败'}`);
            }
          }
        } catch (error) {
          console.error(`删除设备${device.id}时发生错误 (尝试 ${retryCount + 1}):`, error);
          if (retryCount === maxRetries) {
            failCount++;
            errors.push(`设备${device.id}: ${(error as Error).message}`);
          }
        }
        
        retryCount++;
        
        // 如果不是最后一次尝试且删除失败，等待更长时间再重试
        if (retryCount <= maxRetries && !deleteSuccess) {
          await new Promise(resolve => setTimeout(resolve, 800));
        }
      }
      
      // 每个设备删除完成后添加延迟，避免请求过于频繁
      if (i < selectedDevices.value.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 500));
      }
    }

    // 🔥 新增：将成功删除的设备的ESN重新添加回待入网设备列表
    if (successfullyDeletedDevices.length > 0) {
      let addedEsnCount = 0;
      for (const device of successfullyDeletedDevices) {
        if (device.esn) {
          const addSuccess = module_store.addPendingDevice(device.esn);
          if (addSuccess) {
            addedEsnCount++;
            console.log(`✅ [DEBUG] 已将ESN重新添加回待入网设备列表: ${device.esn}`);
          } else {
            console.warn(`⚠️ [DEBUG] ESN已存在于待入网设备列表中: ${device.esn}`);
          }
        }
      }
      console.log(`📊 [DEBUG] 批量删除后，已将 ${addedEsnCount} 个ESN重新添加回待入网设备列表`);
      console.log(`📊 [DEBUG] 当前待入网设备数量: ${module_store.pendingDevices.length}`);
    }

    // 显示批量删除结果
    if (successCount > 0 && failCount === 0) {
      ElMessage.success(`成功删除 ${successCount} 个设备！`);
    } else if (successCount > 0 && failCount > 0) {
      ElMessage.warning(`成功删除 ${successCount} 个设备，${failCount} 个设备删除失败`);
      console.warn('删除失败的设备:', errors);
    } else {
      ElMessage.error(`删除失败，${failCount} 个设备删除失败`);
      console.error('删除失败的设备:', errors);
    }

    // 更新设备列表，移除成功删除的设备
    if (successfullyDeletedIds.length > 0) {
      const remainingCount = await updateDeviceListAfterDelete(successfullyDeletedIds);
      
      // 触发统计数据更新 - 通过访问getter来强制重新计算
      const totalDevices = module_store.get_all_devices_num;
      const onlineDevices = module_store.online_num;
      
      console.log(`📊 设备统计更新 - 总设备数: ${totalDevices}, 在线设备数: ${onlineDevices}`);
      ElMessage.info(`批量删除完成，当前网关设备数量：${remainingCount}/30`);

      // 🔥 新增：删除设备后，自动更新表单中的设备ID为下一个可用ID
      const nextAvailableId = getNextAvailableDeviceId();
      if (nextAvailableId && formData.value.deviceId) {
        // 如果当前表单中的设备ID已被删除，或者为了展示ID回收效果，更新为下一个可用ID
        const wasCurrentIdDeleted = successfullyDeletedIds.includes(formData.value.deviceId);
        if (wasCurrentIdDeleted || successfullyDeletedIds.length > 0) {
          formData.value.deviceId = nextAvailableId;
          console.log(`🔄 [DEBUG] 设备ID已回收，表单设备ID更新为: ${nextAvailableId}`);
        }
      }

      // 发送一个自定义事件，以清除所有设备的闪烁状态
      const event = new CustomEvent('custom-event', { detail: { type: 'reset' } });
      window.dispatchEvent(event);
    }

  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除设备失败:', error);
      ElMessage.error('批量删除设备失败：' + (error as Error).message);
    }
  } finally {
    loading.value = false;
  }
}

// 处理设备选择变化
const handleDeviceSelectionChange = (selection: Device[]) => {
  selectedDevices.value = selection;
  console.log('选中的设备:', selection);
}

// 切换到指定网关
const switchToGateway = (gateway: Gateway) => {
  formData.value.gatewayName = gateway.name || `默认网关${gateway.id}`
  formData.value.gatewayId = gateway.id
  
  // 切换网关
  gateway_store.switchGateway(parseInt(gateway.id))
  
  updateDeviceListDisplay()
  ElMessage.success(`已切换到${gateway.name || `默认网关${gateway.id}`}`)
}

// 查看网关详情
const viewGatewayDetails = (gateway: Gateway) => {
  ElMessageBox.alert(
    `网关名称: ${gateway.name}\n网关ID: ${gateway.id}\nESN号: ${gateway.esn}\n设备数量: ${getGatewayNumber(gateway.ip as string)}/30\n状态: ${gateway.isConnected? '在线' : '离线'}`,
    '网关详情',
    {
      confirmButtonText: '确定'
    }
  )
}

const updateTotalDeviceCount = async () => {
    const allDevices = await module_store.getAllDevices();
    totalDeviceCount.value = allDevices.length;
};


// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
  formData.value = {
    gatewayName: '',
    gatewayId: '',
    deviceName: '',
    esnNumber: '',
    deviceId: getNextAvailableDeviceId() || 1,
    powerType: ''
  }
  selectedDevices.value = []
}

// 确认配置
const handleConfirm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 验证必填参数
    const { gatewayName, gatewayId, deviceName, deviceId, powerType, esnNumber } = formData.value;
    if (!gatewayName || !gatewayId || !deviceName || !deviceId || !powerType || !esnNumber) {
      ElMessage.error('所有参数都不能为空');
      return;
    }

    // 获取当前网关IP
    const selectedGateway = gatewayList.value.find(g => g.name === gatewayName);
    if (!selectedGateway) {
      ElMessage.error('选中的网关不存在');
      return;
    }
    
    loading.value = true
    
    // 构建添加设备的payload，参考CmdCenter.vue的实现
    const payload = {
      action: 'gateway',
      type: 'add',
      gatewayId: selectedGateway.ip,
      esn: esnNumber,
      id: deviceId,
    };

    console.log('发送添加设备指令:', payload);
    
    // 发送WebSocket指令
    const response = await sendWebSocketCommand(payload);
    console.log('添加设备响应:', response);
    
    // 处理响应
    let parsedResponse = response;
    if (typeof response === 'string') {
      try {
        parsedResponse = JSON.parse(response);
      } catch (e) {
        console.warn('响应不是有效的JSON:', response);
      }
    }
    
    // 检查是否成功
    if (parsedResponse && parsedResponse.success) {
      ElMessage.success(`设备 ${deviceName} (ID: ${deviceId}) 添加成功!`);
      
      // 成功添加后，从待入网列表中移除该ESN
      module_store.removePendingDevice(esnNumber);
      
      // 刷新设备列表
      await module_store.setDevice(selectedGateway.ip, gateway_store.gateway_deviceList);
      
      emit('confirm', formData.value)
      dialogVisible.value = false
    } else {
      const errorMsg = parsedResponse?.message || '添加设备失败';
      ElMessage.error(errorMsg);
    }
    
  } catch (error) {
    console.error('添加设备失败:', error);
    ElMessage.error('添加设备失败：' + (error as Error).message);
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  ElMessageBox.confirm('确定要关闭配置对话框吗？未保存的更改将丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    dialogVisible.value = false
    handleReset()
  }).catch(() => {
    // 用户取消关闭
  })
}

// 监听对话框打开，重置表单
watch(dialogVisible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      handleReset()
    })
    // 对话框打开时加载设备自定义名称
    loadDeviceCustomNames()
  }
})

// 初始化 WebSocket 实例和组件数据
onMounted(async () => {
  // 获取 WebSocket 实例
  wsInstance.value = WebsocketIo.getInstance();
  
  // 加载网关列表数据
  await gateway_store.fetchGatewayList();
  
  // 初始化时更新设备列表显示
  updateDeviceListDisplay()
  // 更新设备总数
  await updateTotalDeviceCount()
  
  // 初始化设备列表数据
  await updateDeviceListData()
})

// 监听网关设备列表变化
watch(() => module_store.gateway_deviceList, async () => {
  updateDeviceListDisplay()
  updateTotalDeviceCount()
  
  // 更新设备列表数据
  await updateDeviceListData()
  
  // 触发全局设备统计更新事件
  const currentIp = gateway_store.currentIp;
  if (currentIp) {
    const currentDevices = module_store.gateway_deviceList.get(currentIp) || [];
    const onlineDevices = currentDevices.filter(device => device?.status).length;
    const totalDevices = currentDevices.length;
    
    // 发送设备统计更新事件
    const statsUpdateEvent = new CustomEvent('websocket-message', {
      detail: {
        action: 'deviceStatsUpdate',
        data: {
          gatewayIp: currentIp, // 添加网关IP信息
          totalDevices,
          onlineDevices,
          deviceDetails: currentDevices.map(device => ({
            deviceId: device?.deviceId || '',
            deviceName: device?.name || `监测点${device?.deviceId}`,
            gatewayIp: currentIp,
            isOnline: device?.status || false,
            esn: device?.esn || '',
            lastSeen: Date.now()
          }))
        }
      }
    });
    window.dispatchEvent(statsUpdateEvent);
  }
}, { deep: true })
</script>

<style scoped lang="less">
:deep(table) {
  width: 100%!important;
}
.gateway-config-dialog {
  .gateway-form {
    padding: 20px 0;
  }
}

.readonly-input {
  :deep(.el-input__inner) {
    background-color: #2c2c2c;
    cursor: not-allowed;
    color: #a9a9a9;
  }
}

.auto-icon {
  color: #409eff;
  cursor: pointer;

  &:hover {
    color: #66b1ff;
  }
}

.device-pagination {
  margin-top: 10px;
  text-align: center;
}

.device-management {
  .device-actions {
    display: flex;
    justify-content: flex-start; // 修改为 flex-start
    gap: 10px;
  }

  .device-table {
    width: 100%; // 添加宽度100%
    margin-bottom: 15px;
  }

  .device-list-pagination {
    display: flex; // 添加 flex
    justify-content: center; // 添加居中
    margin-top: 15px; // 调整间距
  }
}

.gateway-management {
  .gateway-table {
    width: 100%; // 添加宽度100%
    margin-top: 10px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 设备名称编辑相关样式 */
.name-edit-container {
  display: flex;
  align-items: center;
  gap: 4px;
}

.name-display-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.name-display-container:hover .el-button {
  opacity: 1;
}

.name-display-container .el-button {
  opacity: 0;
  transition: opacity 0.2s;
}

.edit-actions {
  display: flex;
  gap: 2px;
}

.edit-actions .el-button {
  padding: 4px 6px;
  min-height: auto;
}

.reboot-dialog {
  .reboot-content {
    text-align: center;
    padding: 20px;

    .reboot-icon {
      font-size: 48px;
      color: #f56c6c;
      margin-bottom: 20px;
    }

    .reboot-title {
      font-size: 20px;
      font-weight: 600;
      color: #e0e0e0;
      margin-bottom: 15px;
    }

    .reboot-message {
      color: #a9a9a9;
      margin-bottom: 20px;
      line-height: 1.6;
    }

    .countdown-progress {
      margin-top: 20px;
    }
  }
}

.add-device-dialog {
  .add-device-form {
    padding: 20px 0;
  }

  .esn-auto-section {
    width: 100%;
  }

  .readonly-input {
    :deep(.el-input__inner) {
      background-color: #2c2c2c;
      cursor: not-allowed;
      color: #a9a9a9;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}

// 暗黑主题样式覆盖
:deep(.el-form-item__label) {
  color: #a9a9a9;
}
:deep(.el-table__body-wrapper) {
  width: 100%;
}
:deep(el-table__body) {
  width: 100%;
}
:deep(.el-input__inner),
:deep(.el-select__wrapper) {
  background-color: #2c2c2c;
  border: 1px solid #4d4d4d;
  color: #e0e0e0;
  box-shadow: none;

  &:focus {
    border-color: #409eff;
  }
}

:deep(.el-table) {
  background-color: #1e1e1e;
  color: #e0e0e0;

  th {
    background-color: #2c2c2c;
    color: #a9a9a9;
    border-bottom: 1px solid #4d4d4d;
  }

  td {
    border-bottom: 1px solid #4d4d4d;
  }

  .el-table__row {
    background-color: #1e1e1e;

    &:hover {
      background-color: #0a0a0a;
    }
  }
}

:deep(.el-divider__text) {
  background-color: #1e1e1e;
  color: #a9a9a9;
}

:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;

  &:hover {
    background-color: #66b1ff;
    border-color: #66b1ff;
  }
}

:deep(.el-button--danger) {
  background-color: #f56c6c;
  border-color: #f56c6c;

  &:hover {
    background-color: #f78989;
    border-color: #f78989;
  }
}

:deep(.el-pagination) {
  .el-pager li {
    background-color: #2c2c2c;
    color: #a9a9a9;

    &.is-active {
      background-color: #409eff;
      color: white;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 2vh auto;
  }

  .gateway-form {
    .el-col {
      margin-bottom: 10px;
    }
  }

  .device-management {
    .device-actions {
      flex-direction: column;

      .el-button {
        width: 100%;
      }
    }
  }
}
/* 解决表格悬停背景色问题 */
:deep(.el-table__body tr:hover > td) {
  background-color: #383838 !important;
}

.gateway-form .el-input.is-readonly .el-input__inner {
  background-color: #2c2c2c;
  border-color: #4a4a4a;
  color: #a9a9a9;
  cursor: default;
}

/* 设备信息编辑相关样式 */
.device-edit-content {
  .el-form {
    .form-tip {
      font-size: 12px;
      color: #909399;
      margin-top: 4px;
    }
    
    .el-form-item {
      margin-bottom: 20px;
    }
  }
}

/* 优化标签样式 */
:deep(.el-tag) {
  font-weight: 500;
  border-radius: 4px;
  
  &.el-tag--success {
    background-color: rgba(103, 194, 58, 0.1);
    border-color: #67c23a;
    color: #67c23a;
  }
  
  &.el-tag--warning {
    background-color: rgba(245, 108, 108, 0.1);
    border-color: #f56c6c;
    color: #f56c6c;
  }
  
  &.el-tag--danger {
    background-color: rgba(245, 108, 108, 0.1);
    border-color: #f56c6c;
    color: #f56c6c;
  }
  
  &.el-tag--info {
    background-color: rgba(144, 147, 153, 0.1);
    border-color: #909399;
    color: #909399;
  }
}

/* 设备操作按钮样式 */
.device-actions {
  display: flex;
  gap: 8px;
  
  .el-button {
    padding: 4px 8px;
    font-size: 12px;
  }
}

/* 供电方式编辑对话框样式 */
.power-type-edit-content {
  .device-info {
    background-color: #f5f7fa;
    padding: 15px;
    border-radius: 6px;
    margin-bottom: 20px;
    
    p {
      margin: 8px 0;
      color: #606266;
      
      strong {
        color: #303133;
      }
    }
  }
  
  .power-type-selection {
    h4 {
      margin-bottom: 15px;
      color: #303133;
      font-size: 14px;
    }
    
    :deep(.el-radio-group) {
      display: flex;
      flex-direction: column;
      gap: 12px;
      
      .el-radio {
        margin-right: 0;
        
        .el-radio__label {
          font-size: 14px;
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>